"""
日志配置模块
"""

import sys
import logging
from pathlib import Path
from loguru import logger

from .config import settings


class InterceptHandler(logging.Handler):
    """
    拦截标准库日志并重定向到loguru
    """
    
    def emit(self, record):
        # 获取对应的loguru级别
        try:
            level = logger.level(record.levelname).name
        except ValueError:
            level = record.levelno
        
        # 查找调用者
        frame, depth = logging.currentframe(), 2
        while frame.f_code.co_filename == logging.__file__:
            frame = frame.f_back
            depth += 1
        
        logger.opt(depth=depth, exception=record.exc_info).log(level, record.getMessage())


def setup_logging():
    """配置日志"""
    # 移除所有默认处理器
    logger.remove()
    
    # 添加控制台输出
    logger.add(
        sys.stdout,
        format="{time:YYYY-MM-DD HH:mm:ss} | {level} | {message}",
        level=settings.LOG_LEVEL,
        colorize=True,
    )
    
    # 添加文件输出
    logs_path = Path("logs")
    logs_path.mkdir(exist_ok=True)
    
    logger.add(
        logs_path / "ecom_pilot_{time:YYYY-MM-DD}.log",
        rotation="00:00",  # 每天轮换
        retention="7 days",  # 保留7天
        format="{time:YYYY-MM-DD HH:mm:ss} | {level} | {message}",
        level=settings.LOG_LEVEL,
    )
    
    # 拦截标准库日志
    logging.basicConfig(handlers=[InterceptHandler()], level=0)
    
    # 拦截第三方库日志
    for _log in ["uvicorn", "uvicorn.error", "fastapi"]:
        _logger = logging.getLogger(_log)
        _logger.handlers = [InterceptHandler()]
    
    return logger 